package org.codefinger.dao.impl.mysql;

import javax.sql.DataSource;

import org.codefinger.dao.impl.Querier;
import org.codefinger.dao.impl.QueryParam;
import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.sql.Column;
import org.codefinger.dao.impl.sql.Group;
import org.codefinger.dao.impl.sql.Having;
import org.codefinger.dao.impl.sql.Join;
import org.codefinger.dao.impl.sql.Order;
import org.codefinger.dao.impl.sql.Source;
import org.codefinger.dao.impl.sql.Union;
import org.codefinger.dao.impl.sql.Where;

public class MySQLQuerier extends Querier {

	public MySQLQuerier(//
			DataSource dataSource,//
			boolean isDistinct, //
			Column column, //
			Source from, //
			Join join,//
			Where where, //
			Group group, //
			Having having, //
			Union union, //
			Order order,//
			String[] aliases) {

		super(dataSource,//
				isDistinct,//
				column, //
				from, //
				join, //
				where, //
				group, //
				having,//
				union, //
				order,//
				aliases);
	}

	@Override
	protected SQLVisitor visitPaging(QueryParam queryParam) {
		SQLVisitor visitor = new SQLVisitor(queryParam);
		if (isDistinct) {
			visitor.appendSQL("SELECT DISTINCT ");
		} else {
			visitor.appendSQL("SELECT ");
		}
		column.visitAlias(visitor);
		from.visit(visitor);
		if (join != null) {
			join.visit(visitor);
		}
		if (where != null) {
			where.visit(visitor);
		}
		if (group != null) {
			group.visit(visitor);
		}
		if (having != null) {
			having.visit(visitor);
		}
		if (union != null) {
			union.visit(visitor);
		}
		if (order != null) {
			order.visit(visitor);
		}
		
		int pageIndex = queryParam.getPageIndex();
		if (pageIndex < 1) {
			pageIndex = 1;
		}
		int pageSize = queryParam.getPageSize();
		if (pageSize < 0) {
			pageSize = 0;
		}

		visitor.appendSQL(" LIMIT ");
		visitor.appendSQL(Integer.toString((pageIndex - 1) * pageSize));
		visitor.appendSQL(',');
		visitor.appendSQL(Integer.toString(pageSize));
		
		return visitor;
	}

}
